package com.vf.admin.client.controller.pay.apple;

import cn.hutool.core.util.ObjectUtil;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.result.PayInfoResult;
import com.vf.admin.client.service.*;
import com.vf.admin.common.Constants;
import com.vf.admin.common.entity.Result;
import com.vf.admin.fiwork.controller.AppDailyTasController;
import com.vf.admin.fiwork.util.IOSVerify;
import com.vf.admin.miaodong.entity.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Map;

import static com.vf.admin.common.Constants.*;
import static com.vf.admin.utils.RandomUtil.getOrderIdByUUId;

/**
 * <p>Title : 苹果支付</p>
 * <p>Description : </p>
 * <p>DevelopTools : IDEA</p>
 * <p>DevelopSystem : Windows10</p>
 *
 * @Author : NemoMeng
 * @Date 2023/6/28 15:41
 */
@Controller
@CrossOrigin
@RequestMapping(value = "/api/applePay")
public class ApiApplePayController extends ClientBaseController {


    private Logger logger = LoggerFactory.getLogger(getClass());

    //appSetup设置
    @Autowired
    private AppSetupService appSetupService;
    //用户信息
    @Autowired
    private AppUserService appUserService;
    //充值金额信息
    @Autowired
    private AppCzMoneyService appCzMoneyService;
    //钱包订单
    @Autowired
    private AppOrderService appOrderService;


    @Autowired
    private AppMingXiZuanShiService appMingXiZuanShiService;
    @Autowired
    private AppMingxiChongzhiService appMingxiChongzhiService;
    @Autowired
    private AppDailyTasController appDailyTasController;
    @Autowired
    private AppPrivilegeService appPrivilegeService;
    @Autowired
    private AppInvitationRecordService appInvitationRecordService;


    //会员充值金额信息
    @Autowired
    private VipPackageService vipPackageService;
    //vip订单
    @Autowired
    private VipOrderService vipOrderService;



    /**
     * 下单操作 分钱包 vip
     */
    @RequestMapping(value = "/recharge", method = RequestMethod.POST)
    @ResponseBody
    public Result transactionsH5(Integer type, Integer projectId) {

        //钱包
        if (type == 1) {
            try {
                //提示
                AppSetup setup = appSetupService.get();
                if (setup.getOpenRecharge() == 0) {
                    return this.errorJSON(setup.getRechargeTip());
                }
                //获取用户信息
                AppUser user = appUserService.get(getUserId());
                AppCzMoney appCzMoney = appCzMoneyService.get(projectId);
                //添加订单记录
                AppOrder appOrder = new AppOrder();
                appOrder.setCreatetime(new Date());
                appOrder.setOrdernum(getOrderIdByUUId());//生成订单号
                appOrder.setCzMoneyId(appCzMoney.getId());
                appOrder.setMoney(new BigDecimal(appCzMoney.getMoney()));
                appOrder.setStatus(Constants.dingdan_status_dfk);//默认 1、代付款
                appOrder.setType(dingdan_zhiFuLeiXing_apple);    //订单支付类型  默认 1、支付宝 2、微信 3、苹果  4、杉德支付宝 5、杉德微信
                appOrder.setUserid(user.getId());//下单人信息
                appOrder.setPic(user.getPic());
                appOrder.setNick(user.getNick());
                appOrder.setPhone(user.getLoginname());
                appOrder.setNum(appCzMoney.getDiamonds().add(appCzMoney.getGive()));
                appOrderService.save(appOrder);
                if (ObjectUtil.isEmpty(appOrder)) {
                    return this.errorJSON("充值失败，请您重新充值!");
                }
                PayInfoResult payInfoResult = new PayInfoResult();
                payInfoResult.setOrderNo(appOrder.getOrdernum());
                return this.sucessJSON(payInfoResult);
            } catch (Exception e) {
                logger.error("充值异常:", e);
                return this.errorJSON("服务器繁忙，请您稍后重试!");
            }
        }
        //会员
        if (type == 2) {
            try {
                //提示
                AppSetup setup = appSetupService.get();
                if (setup.getOpenBuyVip() == 0) {
                    return this.errorJSON(setup.getBuyVipTip());
                }
                //获取用户信息
                AppUser user = appUserService.get(getUserId());
                VipPackage vipPackage = vipPackageService.info(projectId);
                //添加订单记录
                VipOrder vipOrder = new VipOrder();
                vipOrder.setUserId(user.getId());
                vipOrder.setOrderNo(getOrderIdByUUId());//订单号
                vipOrder.setVipPackageId(vipPackage.getId());//
                vipOrder.setStatus(0);  //0待支付 1已支付
                vipOrder.setPayType("ios");
                vipOrder.setCreateTime(new Date());
                vipOrder.setType(Constants.dingdan_zhiFuLeiXing_apple); //订单支付类型  默认 1、支付宝 2、微信 3、苹果  4、杉德支付宝 5、杉德微信
                vipOrderService.save(vipOrder);//
                if (ObjectUtil.isEmpty(vipOrder)) {
                    return this.errorJSON("充值失败，请您重新充值!");
                }
                PayInfoResult payInfoResult = new PayInfoResult();
                payInfoResult.setOrderNo(vipOrder.getOrderNo());
                return this.sucessJSON(payInfoResult);
            } catch (Exception e) {
                logger.error("充值异常:", e);
                return this.errorJSON("服务器繁忙，请您稍后重试!");
            }
        }
        return this.errorJSON("请求参数不正确!");
    }

    /**
     * ios内购回调
     *
     * @param receipt
     * @return
     */
    @RequestMapping(value = "/iosPaySuccess", method = RequestMethod.POST)
    @ResponseBody
    public Result iosPaySuccess(@RequestParam("orderNo") String orderNo, @RequestParam("receipt") String receipt) {
        try {
            receipt = URLDecoder.decode(receipt, "utf-8");
            logger.info("----------------------receipt Str:" + receipt);
            Map<String, Object> result = IOSVerify.buyAppVerify(receipt);
            if (result.get("success").toString().equals("true")) {
//                String externalOrderNo = (String) result.get("transaction_id");

                if (ObjectUtil.isNotEmpty(orderNo)) {
                    //钱包
                    AppOrder order = appOrderService.getByOrdernum(orderNo, Constants.dingdan_zhiFuLeiXing_apple, dingdan_status_dfk);
                    if (ObjectUtil.isNotEmpty(order)) {

                        AppUser user = appUserService.get(order.getUserid());
                        //存在则更改预订单支付状态
                        appOrderService.updateStastusYzf(order.getOrdernum(), Constants.dingdan_zhiFuLeiXing_apple);
                        BigDecimal getDiamond = order.getNum();
                        //添加用户钻石金额
                        appUserService.updateZuanShi(user.getId(), getDiamond);
                        //增加用户累积充值金额
                        appUserService.updateLeijiChongzhi(user.getId(), order.getMoney());
                        //添加钻石明细
                        appMingXiZuanShiService.addMingxi(user.getId(), getDiamond, 1, "钻石充值");
                        //添加充值明细
                        appMingxiChongzhiService.addMingxi(user.getId(), getDiamond, 1, order.getMoney(), order.getOrdernum(),user.getMobileSpec());
                        //完成充值任务
                        appDailyTasController.getAwardOnce(order.getUserid(), ClientConstants.TaskOnce.RECHARGE_FIRST);
                        //如果有上级发放用户充值提成
                        addAward(order);
                        //升级贵族
                        appPrivilegeService.isUpLevel(user);
                    }
                    //vip充值
                    VipOrder byOrderNum = vipOrderService.getByOrderNum(orderNo, dingdan_zhiFuLeiXing_apple, 0);
                    if (ObjectUtil.isNotEmpty(byOrderNum)) {

                        vipOrderService.successCall(orderNo);
                    }
                }
            } else {
                return errorJSON("IOS内购验证失败");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;

    }


    /**
     * 邀请用户充值增加父级提成
     *
     * @param order
     */
    public void addAward(AppOrder order) {
        AppInvitationRecord record = appInvitationRecordService.getShangji(order.getUserid());
        if (record != null) {
            AppSetup appSetup = appSetupService.get();
            BigDecimal divide = order.getNum().multiply(appSetup.getRechargeInvite()).setScale(2, BigDecimal.ROUND_HALF_UP);
            appUserService.addDiamonds(record.getPuserid(), divide, "邀请用户充值提成");
        }
    }
}
